package juc;

import java.util.concurrent.CountDownLatch;

/**
 * Description:
 *      两个线程交替输出
 *                 第一个线程：1 2 3 4 5 6 7
 *                 第二个线程： A B C D E F G
 *        输出结果：1A2B3C4D5E6F7G
 */
public class Test06 {

    public static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args){
        char[] nums = "1234567".toCharArray();
        char[] chars = "ABCDEFG".toCharArray();

        Object lock = new Object();

        Thread t1 = new Thread(()->{
            try{
                synchronized (lock){
                    countDownLatch.countDown(); //减去1
                    for(char temp: nums){
                        System.out.println(temp);
                        lock.notify();
                        lock.wait();
                    }
                    lock.notify(); //清空等待队列
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t1");

        Thread t2 = new Thread(()->{
            try{

                countDownLatch.await(); //等待，下面的代码一定不会先运行。这里使用的是await，不是wait

                synchronized (lock){
                    for(char temp: chars){
                        System.out.println(temp);
                        lock.notify();
                        lock.wait();
                    }
                    lock.notify(); //清空等待队列
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t2");

        t1.start();
        t2.start();
    }
}
